<?php

/**
* alltosun.com 用户订单控制器 index.php
* ============================================================================
* 版权所有 (C) 2009-2014 北京互动阳光科技有限公司，并保留所有权利。
* 网站地址: http://www.alltosun.com
* ----------------------------------------------------------------------------
* 许可声明: 这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
* ============================================================================
* $Author: 吴松键 (wusj@alltosun.com) $
* $Date: 2014-9-10 上午11:54:35 $
* $Id$
*/

class Action
{
    private $user_id;

    public function __construct()
    {
        //error_reporting(E_ALL & ~E_NOTICE);
        checkLogin(get_url());
        $this->user_id = user_helper::get_user_id();
    }

    /**
     * 订单列表
     */
    public function index()
    {
        if (!$this->user_id) {
            return array('请登陆后进行操作', 'error', AnUrl('index'));
        }

        $progress = Request::getParam('progress', 0);
        if ($progress == 0 OR $progress == 'all') {
            $progress = '';
        }

        Response::assign('progress', $progress);

        if (is_mobile()) {
            $order_list = _widget('order')->get_list();
            Response::assign('order_list', $order_list);
        }

        display_template('user_order.html');
    }

    /**
     * ajax 获取订单列表
     */
    public function load_list()
    {
        $page_no = Request::getParam('page_no', 1);

        $order_list = _widget('order')->get_list(array('page_no'=>$page_no));

        Response::assign('order_list', $order_list);

        Response::display('m/load_order_list.html');
    }

    /**
     * 查看订单详情
     */
    public function __call($action = '', $param = array())
    {
        $is_direct_pay = Request::Get('direct_pay', 0);
        $showwxpaytitle = Request::Get('showwxpaytitle', 0);

        $id = (int)$action;
        if (!$id) {
            return array('请选择需要操作的订单', 'error', AnUrl('order'));
        }

        if (!$this->user_id) {
            return array('请登陆后进行操作', 'error', AnUrl('index'));
        }
        if($showwxpaytitle && $is_direct_pay) {
            if(is_weixin() && !isset($_SESSION['open_id']) && empty($_SESSION['open_id'])) {
                Response::redirect(AnUrl("openapi/weixin/simple?redirect_url=".urlencode('order/'.$id.'?showwxpaytitle=1&direct_pay=1')));
            }
        }
        /*
        order_helper::auto_status($id); // 自动更新状态
        */
        $order_info   = _uri('order', $id);
        if ($order_info['user_id'] != $this->user_id) {
            return array('您不能操作别人的订单', 'error', AnUrl('order'));
        }

        $order_detail = order_helper::get_order_relation_by_order_id($id);
        $cancel_time = strtotime($order_info['add_time'])+24*3600;
        $end_time    = $cancel_time - time();
        if ($end_time > 0) {
            $hour = floor($end_time/3600);
            $min  = floor($end_time%3600/60);
        } else {
            $hour = 0;
            $min  = 0;
            $end_time = 0;
        }

        // 获取地址列表
        $address_list = _widget('address')->get_list();
        $address_info = array();
        if ($address_list) {
            foreach ($address_list as $k=>$v) {
                if ($order_info['province'] == $v['province'] && $order_info['district'] == $v['district'] && $order_info['receiver'] == $v['receiver'] && $order_info['address'] == $v['address'] && $order_info['mobile'] == $v['mobile']) {
                    $address_info = $v;
                    break;
                }
            }
        }
        if (empty($address_info)) {
            $address_info = array(
                'receiver'    => $order_info['receiver'],
                'address'     => $order_info['address'],
                'mobile'      => $order_info['mobile'],
                'province'    => $order_info['province'],
                'city'        => $order_info['city'],
                'district'    => $order_info['district'],
                'province_id' => _uri('provincial', array('title'=>$order_info['province']), 'id'),
                'city_id'     => _uri('provincial', array('title'=>$order_info['city']), 'id'),
                'district_id' => _uri('provincial', array('title'=>$order_info['district']), 'id'),
            );
        }

        // 计算送货时间
        if ($order_info['deliver_time'] > $order_info['add_time']) {
            $time = strtotime($order_info['deliver_time'])+3*24*3600;
        } elseif ($order_info['pay_time'] > $order_info['add_time']) {
            $time = strtotime($order_info['pay_time'])+3*24*3600;
        } else {
            $time = time()+3*24*3600;
        }
        $weekarray = array("日","一","二","三","四","五","六");
        $sentTime = (int)date('m', $time).'月'.(int)date('d', $time).'日'.'[周'.$weekarray[date('w', $time)].']';

        // 快递列表
        $express_list = _model('express')->getList(array('status'=>1));
        foreach ($express_list as $k=>$v) {
            $express_list[$k]['price_info'] = express_helper::get_express_price_by_order($id, $v['id'], 0,$order_info['province'], $order_info['city'], $order_info['district']);
        }
        if (isset($order_info['express_id']) && $order_info['express_id']) {
            $order_info['express_title'] = _uri('express', $order_info['express_id'], 'title');
        }

        Response::assign('express_list', $express_list);
        Response::assign('address_info', $address_info);
        Response::assign('sentTime', $sentTime);
        Response::assign('address_list', $address_list);
        Response::assign('order_info', $order_info);
        Response::assign('order_detail', $order_detail);
        Response::assign('hour', $hour);
        Response::assign('min', $min);
        Response::assign('end_time', $end_time);
        Response::assign('is_direct_pay', $is_direct_pay);
        display_template('order_detail.html');
    }

    /**
     * 购物车提交到订单
     */
    public function trade()
    {
        $address_id     = Request::getParam('address_id', 0);

        if(is_weixin() && !isset($_SESSION['open_id']) && empty($_SESSION['open_id'])) {
            Response::redirect(AnUrl("openapi/weixin/simple?redirect_url=order/trade"));
        }

        // Liw 添加直接购买的支持
        $direct_sku_id = Request::getParam('sku_id', 0);
        $direct_buy_num    = Request::getParam('num', 0);

        $is_direct_buy = 0;
        if($direct_sku_id) {
            //重置session
            $_SESSION['direct_sku_id'] = $direct_sku_id;
            $_SESSION['direct_buy_num'] = $direct_buy_num;

            if(!$direct_buy_num || $direct_buy_num < 0) {
                return "请选择商品购买数量";
            }
            $direct_sku_info  = _uri('sku', $direct_sku_id);
            if(!$direct_sku_info || $direct_sku_info['status'] != 1) {
                return "您要购买的产品已下架";
            }
            $direct_goods_info = _uri('goods', $direct_sku_info['goods_id']);
            if(!$direct_goods_info || $direct_goods_info['is_sale'] != 1) {
                return "您选择的商品已下架";
            }
            // 验证库存
            if((int)$direct_sku_info['stock'] < $direct_buy_num) {
                return "商品库存不足，已被抢光了";
            }
            $is_direct_buy = 1;
            
        }

        if(!$is_direct_buy) {
            if(isset($_GET['pay_account'])) {
                $pay_account_id = Request::Get('pay_account', '');
                $_SESSION['order_pay_account'] = $pay_account_id;
            } elseif(isset($_SESSION['order_pay_account'])) {
                $pay_account_id = $_SESSION['order_pay_account'];
            } else {
                return array('亲，没有要下单的商品', 'info', AnUrl('cart'));
            }
            $pay_account_id = (int)$pay_account_id;
            $alipay_account_list = Config::get('alipay_account_list');
            if(!array_key_exists($pay_account_id, $alipay_account_list)) {
                return "未知的支付类型";
            }

            // 按支付宝帐号来支付
            $category_cart_list = cart_helper::category_cart_by_alipay_account();
            if(empty($category_cart_list[$pay_account_id])) {
                return array('没有要下单的商品', 'info', AnUrl('order'));
            }
            $cart_list                     = $category_cart_list[$pay_account_id];
            $cart_num                      = count($cart_list);
            $total_price                   = cart_helper::get_cart_price_total(false, 0, 1, $cart_list);
            $_SESSION['order_pay_account'] = $pay_account_id;

        } else {
            $cart_num = $direct_buy_num;
            // 自己拼装
            $cart_list   = goods_helper::build_direct_buy_cart_list($direct_sku_id, $direct_buy_num);
            $total_price = $direct_sku_info['price']*$direct_buy_num;
            
        }

        //cheers 活动抢购判断 start
        // $goods_count = 0;
        // foreach($cart_list as $k => $v) {
        //     $is_cheers = events_helper::get_qualification($v['goods_id']);
        //     if($is_cheers !== true) {
        //         if(is_array($is_cheers)) {
        //             return $is_cheers;
        //         }
        //     } else {
        //         if($v['goods_num'] > 1) {
        //             $cart_list[$k]['goods_num'] = 1;
        //             $cart_list = serialize($cart_list);
        //             Cookie::set_path(Config::get('cookie_path'));
        //             Cookie::set_domain(Config::get('cookie_domain'));
        //             Cookie::set('cart', $cart_list, time()+7*24*3600);
        //         }
        //         $goods_count = $goods_count + $v['goods_num'];
        //     }
        // }
        // if($goods_count > 1) {
        //     return array('此商品只能购买一件', 'error', AnUrl(''));
        // }
        //cheers 活动抢购判断 end

        // 获取快递列表
        $express_list = _model('express')->getList(array('status'=>1));

        // 取出上次购买信息
        $order_list = _model('order')->getList(array('user_id'=>$this->user_id), ' ORDER BY `add_time` DESC LIMIT 1');
        $invoice_title = '';
        $pay_type = 1;
        $express_id = $express_list[0]['id'];
        $invoice_type = '';
        if ($order_list) {
            $invoice_title = $order_list[0]['invoice_title'];
            $pay_type      = $order_list[0]['pay_type'];
            $invoice_type  = $order_list[0]['invoice_type'];
            if ($order_list[0]['express_id']) {
                $express_id = $order_list[0]['express_id'];
            }
        }
        if ($invoice_type < 1) {
            $invoice_type = 1;
        }
        $express_title = _uri('express', $express_id, 'title');

        // 获取地址列表
        $address_list = _widget('address')->get_list();
        if ($address_list) {
            $use_id = false;
            if ($address_id) {
                $address_info = _uri('address', $address_id);
                if ($address_info['user_id'] == $this->user_id) {
                    $use_id = true;
                }
            }
            if (!$use_id) {
                $address_info = _model('address')->read(array('user_id'=>$this->user_id, 'is_default'=>1));
                if (!$address_info || empty($address_info)) {
                    $address_info = $address_list[0];
                }
            }

            Response::assign('address_info', $address_info);
        }

        // 计算送货时间
        $time = time()+3*24*3600;
        $weekarray = array("日","一","二","三","四","五","六");
        $sentTime = (int)date('m', $time).'月'.(int)date('d', $time).'日'.'[周'.$weekarray[date('w', $time)].']';

        $promotion_info  = promotion_helper::get_promotion_info($total_price);
        if($promotion_info) {
            $total_price_discount -= $promotion_info['offer_price'];
            if($total_price_discount < 0) {
                $total_price_discount = 0;
            }
        } else {
            $total_price_discount = $total_price;
        }

        if($is_direct_buy) {
            Response::assign('is_direct_buy', $is_direct_buy);
            Response::assign('direct_buy_num', $direct_buy_num);
            Response::assign('direct_goods_info', $direct_goods_info);
            Response::assign('direct_sku_info', $direct_sku_info);
        }
        Response::assign('total_price', $total_price);
        Response::assign('total_price_format', number_format($total_price, 2));
        Response::assign('total_price_discount', $total_price_discount);
        Response::assign('total_price_discount_format', number_format($total_price_discount, 2));

        Response::assign('express_title', $express_title);
        Response::assign('express_id', $express_id);
        Response::assign('express_list', $express_list);
        Response::assign('promotion_info', $promotion_info);
        Response::assign('cart_num', $cart_num);
        Response::assign('cart_list', $cart_list);
        Response::assign('address_list', $address_list);
        Response::assign('invoice_title', $invoice_title);
        Response::assign('invoice_type', $invoice_type);
        Response::assign('pay_type', $pay_type);
        Response::assign('sentTime', $sentTime);

        display_template('trade.html');
    }

    /**
     * Ajax提交订单-》pay
     */
    public function pay()
    {
        $address       = Request::Post('address', 0);
        $invoice_title = AnFilter::filter_string(Request::Post('invoice_title', ''));
        $invoice_type  = Request::Post('invoice_type', 0);
        $pay_type      = Request::Post('pay_type', 0);
        $coupon_code   = AnFilter::filter_string(Request::Post('coupon_code', ''));
        $express_id    = Request::Post('express_id', 0);

        // liw add 验证pay_type
        if(!array_key_exists($pay_type, openapi_config::$pay_type)) {
            return "不支持的支付方式";
        }
        // 重置session
        if(isset($_SESSION['direct_sku_id'])) {
            unset($_SESSION['direct_sku_id']);
            unset($_SESSION['direct_buy_num']);
        }
        // Liw 添加直接购买的支持
        $direct_sku_id  = Request::Post('sku_id', 0);
        $direct_buy_num = Request::Post('num', 0);
        $is_direct_buy  = 0;
        if($direct_sku_id) {
            if(!$direct_buy_num || $direct_buy_num < 0) {
                return "请选择商品购买数量";
            }
            $direct_sku_info  = _uri('sku', $direct_sku_id);
            if(!$direct_sku_info || $direct_sku_info['status'] != 1) {
                return "您要购买的产品已下架";
            }
            $direct_goods_info = _uri('goods', $direct_sku_info['goods_id']);
            if(!$direct_goods_info || $direct_goods_info['is_sale'] != 1) {
                return "您选择的商品已下架";
            }
            // 验证库存
            if((int)$direct_sku_info['stock'] < $direct_buy_num) {
                return "商品库存不足，已被抢光了";
            }
            $is_direct_buy = 1;
        }

        if (!$this->user_id) {
            return array('请登录后再购买', 'error', AnUrl('order'));
        }
        if (!$address) {
            return array('请您先填写收货地址再进行付款。', 'error', AnUrl('order'));
        }

        // 获取购物车或直接购买的
        if(!$is_direct_buy) {
            // 根据支付宝帐号来支付
            if(!isset($_SESSION['order_pay_account'])) {
                return array('没有要下的商品', 'error', AnUrl('cart'));
            }
            $pay_account_id      = (int)$_SESSION['order_pay_account'];
            $alipay_account_list = Config::get('alipay_account_list');
            if(!array_key_exists($pay_account_id, $alipay_account_list)) {
                return array('没有要下的商品', 'error', AnUrl('cart'));
            }
            $category_cart_list = cart_helper::category_cart_by_alipay_account();
            if(empty($category_cart_list[$pay_account_id])) {
                return array('很抱歉，没有要下的商品', 'error', AnUrl('cart'));
            }
            $order_details = $category_cart_list[$pay_account_id];
        } else {
            $order_details = goods_helper::build_direct_buy_cart_list($direct_sku_id, $direct_buy_num, true);
        }

        // 总价格
        if($is_direct_buy) {
            $total_cart_price = $direct_sku_info['price']*$direct_buy_num;
        } else {
            $total_cart_price = cart_helper::get_cart_price_total(false, 0, 1, $order_details);
        }

        /* @TODO 取消用户选择快递
        if (!$express_id) {
            return array('缺少必要参数，请从来源处重新发起支付请求', 'error', AnUrl('order'));
        }*/
        if (!$order_details) {
            return array('缺少必要参数，请从来源处重新发起支付请求', 'error', $is_direct_buy ? AnUrl('order') : AnUrl('cart'));
        }

        //cheers 活动抢购判断 start
        // $goods_count = 0;
        //cheers 活动抢购判断 end
        foreach ($order_details as $k=>$v) {
            //cheers 活动抢购判断 start
            // $goods_count = 0;
            // $is_cheers = events_helper::get_qualification($v['goods_id']);
            // if($is_cheers !== true) {
            //     if(is_array($is_cheers)) {
            //         return $is_cheers;
            //     }
            // } else {
            //     if($v['goods_num'] > 1) {
            //         return array('此商品只能购买一件', 'error', AnUrl(''));
            //     }
            //     $goods_count = $goods_count + $v['goods_num'];
            // }
            //cheers 活动抢购判断 end
            if($v['goods_num'] < 1) {
                return array('商品数量不正确，非法操作！', 'error', $is_direct_buy ? AnUrl('order') : AnUrl('cart'));
            }
            if ($v['is_gift'] == 0) {
                $sku_price = goods_helper::get_sku_id_by_price($v['sku_id']);
                if($sku_price != $v['goods_price']) {
                    return array('商品价格不正确，非法操作！', 'error', $is_direct_buy ? AnUrl('order') : AnUrl('cart'));
                }
            }
        }
        //cheers 活动抢购判断 start
        // if($goods_count > 1) {
        //     return array('此商品只能购买一件', 'error', AnUrl(''));
        // }
        //cheers 活动抢购判断 end
        
        if ($invoice_type < 1 || $invoice_type > 2) {
            $invoice_type = 1;
        }
        if ($invoice_type == 1) {
            $invoice_title = '个人';
        }
        
        if(empty($invoice_title)) {
            return array('请您先填写发票抬头再进行付款。', 'error', $is_direct_buy ? AnUrl('order') : AnUrl('cart'));
        }
        // @TODO 暂时屏蔽发票
        // $invoice_title = '';
        // $invoice_type  = 0;

        $coupon_price = 0;
        $coupon_check_info = coupon_helper::check_is_available($coupon_code, 1);
        // 是否通用打折
        // 计算等分价格
        $coupon_average_price = 0; // 使用优惠券等分优惠价格
        $goods_total_price = 0;
        //计算符合优惠价商品数量
        $goods_type_num = 0;
        $is_general_coupon = false;
        if ($coupon_code && $coupon_check_info && !empty($coupon_check_info)) {
            if ($coupon_check_info['is_all_user'] == 0 && $coupon_check_info['status'] > 2) {
                return '当前优惠券已经被使用了';
            }
            if($coupon_check_info['info'] == 'ok') {
                if($is_direct_buy) {
                    $msg = coupon_helper::check_is_limit($coupon_check_info['category_id'], $coupon_check_info['goods_id'], $coupon_check_info['limit_price'], $order_details);
                } else {
                    $msg = coupon_helper::check_is_limit($coupon_check_info['category_id'], $coupon_check_info['goods_id'],$coupon_check_info['limit_price']);
                }
            } else {
                $msg = $coupon_check_info['info'];
            }

            if ($msg == 'ok') {
                if ($coupon_check_info['info'] == 'ok' || $coupon_check_info['status'] <= 2) {
                    $coupon_price = $coupon_check_info['offer_price'];
                }
                $order_info['coupon_category_id'] = $coupon_check_info['category_id'];
                $order_info['coupon_offer_price'] = $coupon_check_info['offer_price'];
                $order_info['coupon_limit_price'] = $coupon_check_info['limit_price'];
                $order_info['coupon_code']        = $coupon_code;

                foreach ($order_details as $k => $v) {
                    if (coupon_helper::goods_in_coupon($v['goods_id'], $coupon_code) && $v['is_promotion'] == 0 && $v['is_gift'] == 0) {
                        $sku_price = _uri('sku', $v['sku_id'], 'price');
                        $goods_total_price += $v['goods_num']*$sku_price;
                        $goods_type_num++;
                    }
                }
                $coupon_average_price = $coupon_check_info['offer_price']/$goods_total_price;
            }
            // 单品购买的优惠
            elseif($is_direct_buy) {
                $general_coupon_info = coupon_helper::get_general_coupon_info($direct_goods_info['id'], $coupon_code);
                if(!$general_coupon_info) {
                    return $msg;
                }
                if($general_coupon_info['type'] == 'percent') {
                    $is_general_coupon = true;
                    $order_info['coupon_code'] = $coupon_code;
                    // 计算等分价格
                    $general_couponed_price = $total_cart_price*(1-$general_coupon_info['discount']);
                    $total_cart_price       = $total_cart_price*$general_coupon_info['discount'];
                } else {
                    throw new AnMessageException("暂不支持的优惠券方式");
                }
            } else {
                return array($msg, 'error', AnUrl('order/trade'));
            }

        }

        // 获取运费
        /*
        $express_info = express_helper::get_express_price($express_id, $address);
        if (!$express_info || $express_info['info'] != 'ok') {
            return $express_info['info'];
        }
        $express_price = $express_info['price'];
        */
        $express_price = 0;

        $address_info    = _uri('address', $address);
        if($address_info['user_id'] != $this->user_id) {
            return array('对不起，请正确选择您的地址！', 'error', AnUrl('order/trade'));
        }
        $order_price     = $total_cart_price + $express_price;
        $promotion_info  = promotion_helper::get_promotion_info($order_price);
        $promotion_price = 0;
        $promotion_average_price = 0; // 使用满减等分优惠价格
        if (!empty($promotion_info)) {
            if($is_direct_buy) {
                $promotion_average_price = $promotion_info['offer_price']/$total_cart_price; // 计算分优惠价格
            } else {
                $promotion_average_price = $promotion_info['offer_price']/cart_helper::get_cart_price_total(false, false, false); // 计算分优惠价格
            }

            $order_info['promotion_limit_price'] = $promotion_info['limit_price'];
            $order_info['promotion_offer_price'] = $promotion_info['offer_price'];
            $order_price     -= $order_info['promotion_offer_price'];
            $promotion_price += $order_info['promotion_offer_price'];
        }

        if ($coupon_price) {
            $order_price     -= $coupon_price;
            $promotion_price += $coupon_price;
        }
        $order_price = $order_price > 0 ? $order_price : 0;

        $order_info['promotion_price'] = $promotion_price;
        $order_info['user_id']         = $this->user_id;
        $order_info['invoice_title']   = $invoice_title;
        $order_info['invoice_type']    = $invoice_type;
        $order_info['price']           = $order_price;
        $order_info['receiver']        = $address_info['receiver'];
        $order_info['mobile']          = $address_info['mobile'];
        $order_info['province']        = $address_info['province'];
        $order_info['city']            = $address_info['city'];
        $order_info['district']        = $address_info['district'];
        $order_info['address']         = $address_info['address'];
        $order_info['express_id']      = $express_id;
        $order_info['post_price']      = $express_price;
        $order_info['pay_type']        = $pay_type;
        $order_info['progress']        = 1;
        $order_info['origin']          = is_mobile() ? 'm' : 'pc';

        // 找到支付宝帐号
        if($pay_type == 1) {
            $order_info['pay_account']     = _uri('goods', $order_details[0]['goods_id'], 'alipay_account');
        } else {
            // @todo 其他的支付方式
        }

        $order_id = _model('order')->create($order_info);
        // var_dump($order_id);
        // exit;
        if (!$order_id) {
            return array('订单提交失败', 'error', AnUrl('order/trade'));
        }


        //符合优惠价条件全部减免价格
        $goods_coupon_total_price = 0;

        foreach ($order_details as $k=>$v) {
            $goods_num = $v['goods_num'];
            $curr_price = $v['goods_price'] * $v['goods_num'];
            if ($v['is_gift'] == 0) {
                if ($v['is_promotion'] == 1) $goods_num = 1;

                if (coupon_helper::goods_in_coupon($v['goods_id'], $coupon_code)) {
                    //如果是最后一个，则进行减价计算
                    if($goods_type_num == 1) {
                        $curr_price -= coupon_helper::get_coupon_price($coupon_code)-$goods_coupon_total_price;
                    } else {
                        $tmp_goods_coupon_price = $coupon_average_price*$v['goods_price']*$v['goods_num'];
                        $curr_price -= $tmp_goods_coupon_price;
                        $goods_coupon_total_price += $tmp_goods_coupon_price;
                    }
                    $goods_type_num--;
                }

                if ($promotion_average_price && $v['is_promotion'] == 0) $curr_price -= $promotion_average_price*$v['goods_price'];
            }
            $info = array(
                    'sku_id'          => $v['sku_id'],
                    'user_id'         => $this->user_id,
                    'order_id'        => $order_id,
                    'goods_id'        => $v['goods_id'],
                    'goods_num'       => $goods_num,
                    'goods_price'     => $v['goods_price'],
                    'real_price'      => $curr_price,
                    'is_coupon'       => coupon_helper::goods_in_coupon($v['goods_id'], $coupon_code),
                    'is_gift'         => $v['is_gift'],
                    'is_promotion'    => $v['is_promotion']
                );
            $order_relation_id = _model('order_relation')->create($info);
            if (!$order_relation_id) {
                _model('order')->delete($order_id);
                _model('order_relation')->delete(array('order_id'=>$order_id));
                return array('订单提交失败', 'error', AnUrl('order/trade'));
            }
        }

        // 使用优惠券
        if ($coupon_price) {
            $coupon_filter = array(
                    '`status` <='  => 2,
                    'coupon_code' => $coupon_code
            );
            $coupon_info = _uri('coupon_relation', $coupon_filter);
            if(!$coupon_info) {
                return array('没有此优惠卷或者优惠卷已被使用', 'error', AnUrl('order/trade'));
            }
            $coupon_dont_use = 0;
            if ($coupon_info['user_id'] > 0 && $this->user_id != $coupon_info['user_id']) {
                $coupon_dont_use = 1;
            }
            //如果优惠卷所有人可以使用，则永不更新优惠卷的使用状态和用户信息
            $coupon_coupon = _uri('coupon', $coupon_info['coupon_id']);
            if(!$coupon_coupon['is_all_user']) {
                $update_coupon   = _model('coupon_relation')->update($coupon_filter, array('user_id'=>$this->user_id, 'order_id'=>$order_id, 'use_time'=> date('Y-m-d H:i:s', time()), 'status'=>3));
            } else {
                $update_coupon   = _model('coupon_relation')->update($coupon_filter, ' SET `use_num` = `use_num` + 1 ');
            }
            

            // 添加优惠价格
            //$add_coupon_code = _model('order')->update($order_id, array('coupon_price'=>$coupon_price));
            if ($coupon_dont_use) {
                _model('order')->delete($order_id);
                _model('order_relation')->delete(array('order_id'=>$order_id));
                return array('缺少必要参数，请从来源处重新发起支付请求', 'error', AnUrl('cart'));
            }
        }

        // 减少库存 @FIXED 关于是否采用下单即减少库存
        $order_relation_list = _model('order_relation')->getList(array('order_id'=>$order_id));
        $subtract_stock_ids = array();
        foreach ($order_relation_list as $k=>$v) {
            $sku_info = _uri('sku', $v['sku_id']);
            $stock = $sku_info['stock'];
            if ($stock - $v['goods_num'] >= 0) {
                // 减少库存
                _model('sku')->update($v['sku_id'], ' SET `stock` = `stock` - '.$v['goods_num']);
                // 冗余销量字段
                // 下单销量不增加
                // _model('goods')->update($sku_info['goods_id'], ' SET `sale_count` = `sale_count` + '.$v['goods_num']);
                $subtract_stock_ids[] = $v;
            } else {
                _model('order')->delete($order_id);
                _model('order_relation')->delete(array('order_id'=>$order_id));
                foreach ($subtract_stock_ids as $key => $value) {
                    _model('sku')->update($value['sku_id'], ' SET `stock` = `stock` + '.$value['goods_num']);
                    //下单时候  销量不增加
                    // _model('goods')->update($sku_info['goods_id'], ' SET `sale_count` = `sale_count` - '.$v['goods_num']);
                }
                if($is_direct_buy) {
                    return array('商品库存不够了!暂不能购买', 'error', AnUrl('order'));
                } else {
                    return array('有的商品库存不够了，请返回购物车修改！', 'error', AnUrl('cart'));
                }
            }
        }

        // 创建快照
        if ($order_relation_list) {
            foreach ($order_relation_list as $k=>$v) {
                $snapshot_id = goods_helper::create_sku_snapshot($v['sku_id'], $v['id']);
                _model('order_relation')->update(array('id'=>$v['id']), array('sku_snapshot_id'=>$snapshot_id));
            }
        }

        if(!$is_direct_buy) {
            unset($_SESSION['order_pay_account']);
            foreach ($order_details as $k=>$v) {
                _model('cart')->delete(array('user_id'=>$this->user_id, 'sku_id'=>$v['sku_id']));
            }
        }
        // 如果使用优惠券后价格为0 ，不用支付直接购买
        if ($order_price == 0) {
            _model('order')->update($order_id, array('progress'=>10));
            _widget('erp_lenovo.erp_lenovo_order')->AddOrder($order_id);
            Response::redirect(AnUrl('order'));
        } else {
            Response::redirect(order_helper::get_order_pay_url($order_id));
        }
    }

    /**
     * 取消订单
     */
    public function cancel_order()
    {
        $id = Request::getParam('order_id', 0);
        $reason = Request::getParam('reason', '');

        if (!$id) {
            return array('请选择订单', 'error', AnUrl('order'));
        }
        if (!$this->user_id) {
            return array('请登陆后进行操作', 'error', AnUrl('index'));
        }

        $order_info = _uri('order', $id);
        if (!$order_info) {
            return '请选择需要取消的订单';
        }
        if ($order_info['user_id'] != $this->user_id) {
            return '您不能操作别人的订单';
        }
        if ($order_info['status'] != 1) {
            return '当前订单不能操作';
        }

        $deliver = _widget('erp_lenovo.erp_lenovo_order')->Deliver($order_info['id']);
        $has_invoice_no = _widget('erp_lenovo.erp_lenovo_order')->get_invoice_no($order_info['id']);
        if ($deliver === true || $has_invoice_no) {
            return '当前订单不能取消，请收到货后再进行退货';
        }

        if ($order_info['progress'] > 10) {
            return '当前订单不能取消';
        } else if($order_info['progress'] == 10) {
            if (!$reason) {
                return '请选择取消原因';
            }

            // 进入退款流程
            // 1.生成退款定单
            $refund_info = array(
                'user_id'    => $this->user_id,
                'order_id'   => $order_info['id'],
                'receiver'   => $order_info['receiver'],
                'mobile'     => $order_info['mobile'],
                'province'   => $order_info['province'],
                'city'       => $order_info['city'],
                'district'   => $order_info['district'],
                'address'    => $order_info['address'],
                'type'       => 1,
                'pay_type'   => $order_info['pay_type'],
                'note'       => '订单未发货,用户取消,原因：'.$reason,
                'refund_price' => $order_info['price'],
                'real_price'   => $order_info['price'],
                'refund_status' => 15,
                'refund_pay_status' => 0,
                'refund_time' => date('Y-m-d H:i:s'),
                'agree_time'  => date('Y-m-d H:i:s')
            );
            $refund_info_ed = _model('refund')->read(array('order_id'=>$order_info['id']));
            if ($refund_info_ed) {
                return '当前订单已处于退款中，请联系客服！';
            }

            $refund_id = _model('refund')->create($refund_info);
            if (!$refund_id) {
                return '退款失败请联系客服';
            }
            $order_relation_list = _model('order_relation')->getList(array('order_id'=>$order_info['id']));
            if (!$order_relation_list) {
                return '请选择需要退款的订单';
            }
            foreach ($order_relation_list as $k=>$v) {
                $relaiton_info = array(
                    'refund_id' => $refund_id,
                    'order_id'  => $order_info['id'],
                    'order_relation_id' => $v['id'],
                    'sku_snapshot_id'   => $v['sku_snapshot_id'],
                    'refund_num'        => $v['goods_num'],
                    'refund_price'      => $v['goods_price'],
                    'real_price'        => $v['real_price']
                );

                _model('refund_relation')->create($relaiton_info);
            }

            $update = _model('order')->update(array('id'=>$id), array('progress'=>0));
            if (!$update) {
                return '订单取消失败';
            }

            // 返回库存
            order_helper::refund_stock($id);

            // 采用人工干预退款
            if ($order_info['price']) {
                $admin_mobile = Config::get('admin_mobile');
                $admin_email  = ADMIN_EMAIL;
                order_helper::sendExpressMessage('refund_msg_admin', '', $admin_mobile, $admin_email);
            }

            $email = _uri('user', $order_info['user_id'], 'email');
            //order_helper::sendExpressMessage('cancellation_order', array(order_helper::order_id_encode($id)), $order_info['mobile'], $email);
        } else if($order_info['status'] == 1) {
            $update = _model('order')->update(array('id'=>$id), array('progress'=>0));
            // 调用交易关闭接口
            order_helper::alipay_close_trade($order_info['id']);
        }

        if (Request::isAjax()) {
            if ($update) {
                return 'ok';
            } else {
                return '当前订单不能取消';
            }
        }

        Response::redirect(AnUrl('order'));
    }

    /**
     * 删除交易失败的订单
     */
    public function check_delete()
    {
        $id = Request::getParam('id', 0);
        if (!$this->user_id) {
            return '请登陆后进行操作';
        }

        $order_info = _uri('order', $id);
        if (!$order_info) {
            return '当前订单不存在';
        }
        if ($order_info['status'] != 1 || $order_info['progress'] != 0) {
            return '当前订单不能删除';
        }
        if ($order_info['user_id'] != $this->user_id) {
            return '您不能操作别人的订单';
        }

        _model('order')->update(array('id'=>$id), array('status'=>0));

        return 'ok';
    }

    /**
     * 收货
     */
    public function sure_receive()
    {
        $id = Request::getParam('id', 0);
        if (!$this->user_id) {
            return '请登陆后进行操作';
        }

        $filter = array(
                'id'          => $id,
                'user_id'     => $this->user_id,
                'progress'    => 15,
                'status'      => 1
        );

        $order_info = _uri('order', $id);
        if (empty($order_info)) {
            return '当前订单不存在';
        }
        if ($order_info['status'] != 1 || $order_info['progress'] != 15) {
            return '当前订单不在发货状态';
        }
        if ($order_info['user_id'] != $this->user_id) {
            return '您不能操作别人的订单';
        }
        if ($order_info['express_receiver_time'] == '0000-00-00 00:00:00') {
            express_helper::express_info_by_order($order_info['id']);
        }

        _model('order')->update(array('id'=>$id), array('progress'=>20, 'receiver_time'=>date('Y-m-d H:i:s')));

        return 'ok';
    }

    /**
     * ajax 修改订单
     */
    public function edit_order_info()
    {
        $order_id    = Request::getParam('order_id', 0);
        $address     = Request::getParam('address_id', 0);
        $pay_type    = Request::getParam('pay_type', 0);
        $express_id  = Request::getParam('express_id', 0);

        if (!$order_id) {
            return '请选择需修改的订单';
        }
        if (!$pay_type) {
            return '请选择支付方式';
        }

        $old_info     = _uri('order', $order_id);
        if ($old_info['user_id'] != $this->user_id) {
            return '您不能操作别人的订单';
        }

        /* @TODO 屏蔽用户选择快递
        if (!$express_id) {
           return '请选择快递方式';
        }
        $express_info = express_helper::get_express_price_by_order($order_id, $express_id, $address, $old_info['province'], $old_info['city'], $old_info['district']);
        if ($express_info['info'] != 'ok') {
            return $express_info['info'];
        }*/
        //$order_info['post_price']    = $express_info['price'];
        $order_info['post_price']    = 0; //全场包邮

        if ($address) {
            $address_info = _uri('address', $address);
            if($address_info['user_id'] != $this->user_id) {
                return '这个不是您添加的地址';
            }
            $order_info['receiver']      = $address_info['receiver'];
            $order_info['mobile']        = $address_info['mobile'];
            $order_info['province']      = $address_info['province'];
            $order_info['city']          = $address_info['city'];
            $order_info['district']      = $address_info['district'];
            $order_info['address']       = $address_info['address'];
        }

        $order_info['pay_type']      = $pay_type;
        $order_info['express_id']    = $express_id;
        $order_info['price']         = $old_info['price']-$old_info['post_price']+$order_info['post_price'];

        $order_progress = $old_info['progress'];

        if ($order_progress == 1) {
            _model('order')->update(array('id'=>$order_id), $order_info);
            return array(
                'info'=>'ok',
                'url'=>AnUrl(openapi_config::$pay_type[$pay_type]['module'].'?order_id='.$order_id),
                'express_price' => number_format($order_info['post_price'], 2),
                'order_price'   => number_format($order_info['price'], 2)
            );
        } else {
            return '当前订单不能修改支付方式';
        }
    }

    /**
     * ajax 获取订单列表
     */
    public function check_order_list()
    {
        $status = Request::getParam('status', 0);
        if (!$status) {
            return '';
        }

        $order_list = _widget('order')->get_list(array('progress'=>$status, 'per_page'=>1));
        Response::assign('order_list', $order_list);
        $data = Response::fetch(MODULE_PATH.'/user/template/center_order_list.html');

        return array('info'=>'ok', 'data'=>$data, 'count'=>order_helper::get_order_total($status));
    }

    /*
    * 查询订单是否已经支付
    */
   public function query_order()
   {
        if (!$this->user_id) {
            return '请登陆后进行操作';
        }
        $order_id = Request::getParam('order_id', 0);
        if(!$order_id) {
            return array('info'=>'false');
        }
        $order_info = _uri('order', $order_id);
        if($order_info['user_id'] != $this->user_id) {
            return array('info'=>'false');
        }

        if($order_info['progress'] != 1 && $order_info['progress'] != 0) {
            return array('info'=>'ok');
        }
        return array('info'=>'false');

   }

    /**
     * 三维数组转换
     * @return array
     */
    private function exchangeArr($arr)
    {
        foreach ($arr as $key=>$value) {
            foreach ($value as $k=>$v) {
                $new_arr[$k][$key] = $v;
            }
        }
        return $new_arr;
    }
}
?>